#include "Interpreter.hpp"

static void printAliases(Job *job);
static void printAlias(Job *job, const char *name, const char *val);

BUILTIN(alias, "alias")
{
	ShellState *state = job->getState();
	int ret = 0;
	
	if(argv.size() <= 1)
		printAliases(job);
	
	for(size_t ii=1; ii<argv.size(); ii++)
	{
		if(argv[ii]=="-p")
		{
			printAliases(job);
		}
		else
		{
			string aliasname = argv[ii];
			string replacement = "";
			bool assignment = false;
			
			for(size_t jj=0; jj<argv[ii].length(); jj++) {
				if(argv[ii][jj] == '=') {
					aliasname = argv[ii].substr(0, jj);
					replacement = argv[ii].substr(jj+1);
					assignment = true;
					break;
				}
			}
			
			if(assignment) {
				state->aliases[aliasname] = replacement;
			} else if(state->aliases.find(aliasname) == state->aliases.end()) {
				string msg = retprintf("%s: not found", aliasname.c_str());
				job->reportError(msg.c_str());
				ret = 1;
			} else {
				printAlias(job, aliasname.c_str(), state->aliases[aliasname].c_str());
			}
		}
	}
	
	return ret;
}

void printAliases(Job *job)
{
	ShellState *state = job->getState();
	for(map<string,string>::iterator ii=state->aliases.begin(); ii!=state->aliases.end(); ii++)
		printAlias(job, ii->first.c_str(), ii->second.c_str());
}

void printAlias(Job *job, const char *name, const char *val)
{
	job->write("alias ");
	job->write(name);
	job->write("='");
	job->write(val);
	job->write("'\n");
}

BUILTIN(unalias, "unalias")
{
	int ret = 0;
	ShellState *state = job->getState();
	
	for(size_t ii=1; ii<argv.size(); ii++)
	{
		map<string,string>::iterator it = state->aliases.find(argv[ii]);
		
		if(it != state->aliases.end()) {
			state->aliases.erase(it);
		} else {
			string msg = retprintf("%s: not found", argv[ii].c_str());
			job->reportError(msg.c_str());
			ret = 1;
		}
	}
	return ret;
}

